package classes
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	public class QbcHandler extends EventDispatcher
	{
		private static var instance:QbcHandler;
		private var _lastResult:ArrayCollection;
		
		[Bindable ("qbcResult")]
		public function get lastResult():ArrayCollection{
			return _lastResult;
		}
		
		public function performQbc(theColor:uint):void{
			dispatchEvent(new Event("performingQbc"));
			var servletRequest:HTTPService = new HTTPService();
			servletRequest.method = "POST";
			servletRequest.url = Settings.getInstance().qbcServletURL;
			servletRequest.addEventListener(ResultEvent.RESULT, qbcResultHandler);
			servletRequest.send({"color": theColor});
		}
		
		public function QbcHandler(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		private function qbcResultHandler(event:ResultEvent):void{
			_lastResult = Parser.parseServletResult(event);
			if(_lastResult == null){
				dispatchEvent(new Event("qbcError"));
			}else{
				dispatchEvent(new ResultEvent("qbcResult",false,true,lastResult));
			}
		}
		
		public static function getInstance():QbcHandler{
			if(instance == null)
				instance = new QbcHandler();
			return instance;
		}
	}
}